package com.sunhao.springboot_satoken.controller;

import com.sunhao.springboot_satoken.service.CaptchaService;
import com.sunhao.springboot_satoken.utils.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 验证码接口控制器
 * 提供验证码Key获取和验证码图片生成功能
 * 
 * @author SunHao
 */
@RestController
@RequestMapping("/captcha")
@Slf4j
@Validated
@RequiredArgsConstructor
public class CaptchaController {

    private final CaptchaService captchaService;

    private static final String SUCCESS_CODE = "200";
    private static final String SUCCESS_MESSAGE = "操作成功";

    /**
     * 获取验证码Key
     * 前端需要先调用此接口获取唯一的验证码Key，再使用该Key获取验证码图片
     * 
     * @return 包含验证码Key的响应结果
     */
    @GetMapping("/key")
    public Response<Map<String, String>> getCaptchaKey() {
        log.info("获取验证码Key");
        
        // 生成唯一验证码Key
        String captchaKey = captchaService.generateCaptchKey();
        log.debug("生成验证码Key: {}", captchaKey);
        
        // 构建返回数据
        Map<String, String> data = new HashMap<>(1);
        data.put("captchaKey", captchaKey);
        
        return new Response<>(SUCCESS_CODE, SUCCESS_MESSAGE, data);
    }

    /**
     * 获取验证码图片
     * 前端使用从/key接口获取的captchaKey调用此接口，获取验证码图片
     * 
     * @param captchaKey 验证码唯一标识
     * @return 验证码图片的字节数组响应
     */
    @GetMapping("/image")
    public ResponseEntity<byte[]> getCaptchaImage(@RequestParam(required = true) String captchaKey) {
        log.info("获取验证码图片，captchaKey={}", captchaKey);
        
        // 1. 参数校验
        if (!StringUtils.hasText(captchaKey)) {
            log.warn("获取验证码图片失败：captchaKey为空");
            return ResponseEntity.badRequest().build();
        }

        try {
            // 2. 生成验证码图片
            byte[] imageBytes = captchaService.generateCaptchaImage(captchaKey);

            // 3. 验证图片字节数组有效性
            if (imageBytes == null || imageBytes.length == 0) {
                log.error("生成验证码图片失败：图片字节数组为空，captchaKey={}", captchaKey);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }

            // 4. 设置响应头并返回图片
            return ResponseEntity.ok()
                    .contentType(MediaType.IMAGE_PNG)
                    .cacheControl(CacheControl.noStore().noCache().mustRevalidate())
                    .header(HttpHeaders.PRAGMA, "no-cache")
                    .header(HttpHeaders.EXPIRES, "0")
                    .body(imageBytes);
                    
        } catch (IllegalArgumentException e) {
            // 处理参数非法的情况
            log.warn("获取验证码图片失败：{}，captchaKey={}", e.getMessage(), captchaKey);
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            // 处理其他异常
            log.error("获取验证码图片异常，captchaKey={}", captchaKey, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
